//
//  BIDWriteEmailViewController.m
//  商务厅
//
//  Created by mal on 13-12-14.
//  Copyright (c) 2013年 mal. All rights reserved.
//

#import "BIDWriteEmailViewController.h"
#import "BIDMemberListViewController.h"
#import "BIDAccessoryFileTableViewController.h"
#import "BIDUploadFile.h"
#import "BIDCustomTextField.h"
#import "BIDCustomTextView.h"
#import "BIDAddPhotoView.h"
#import "ELCImagePickerHeader.h"
#import "BIDBrowserImageViewController.h"
#import <MobileCoreServices/UTCoreTypes.h>

//添加邮件
static NSString *createEmailURL = @"emailAndroid!addEmail.action";
//存入草稿箱
static NSString *saveToDraftURL = @"emailAndroid!addDraftEmail.action";

@interface BIDWriteEmailViewController ()<BIDAccessoryFileTableViewControllerDelegate, BIDMemberListViewControllerDelegate, BIDUploadFileDelegate, UIAlertViewDelegate, BIDAddPhotoViewDelegate, UITextFieldDelegate, ELCImagePickerControllerDelegate, UINavigationControllerDelegate>
{
    NSString *_memberIds;
    BIDUploadFile *_uploadFile;
    NSArray *_chosenImgArr;
}
@end

@implementation BIDWriteEmailViewController

@synthesize receiverIDs;
@synthesize receiverNames;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title = @"写邮件";
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"写邮件";
    _chosenImgArr = [[NSArray alloc] init];
    _memberIds = @"";
    NSString *strUploadURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], createEmailURL];
    _uploadFile = [[BIDUploadFile alloc] initWithURL:strUploadURL];
    _uploadFile.delegate = self;
    //
    _receiverTF.delegate = self;
    _contentTextView.placeholder = @"请填写邮件内容……";
    _titleTF.inputAccessoryView = self.toolBar;
    _contentTextView.inputAccessoryView = self.toolBar;
    //
    _addPhotoView.delegate = self;
    //
    UIBarButtonItem *btnItem1 = [[UIBarButtonItem alloc] initWithTitle:@"发送" style:UIBarButtonItemStylePlain target:self action:@selector(sendEmail)];
    UIBarButtonItem *btnItem2 = [[UIBarButtonItem alloc] initWithTitle:@"存草稿箱" style:UIBarButtonItemStylePlain target:self action:@selector(saveToDraft)];
    self.navigationItem.rightBarButtonItems = @[btnItem1, btnItem2];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)sendEmail
{
    [self uploadTheEmailWithType:1];
}

- (void)saveToDraft
{
    [self uploadTheEmailWithType:2];
}

//提交或者存入草稿箱
- (void)uploadTheEmailWithType:(NSInteger)type
{
    NSString *strDesURL = @"";
    if(type==1)
    {
        strDesURL = createEmailURL;
    }
    else
    {
        strDesURL = saveToDraftURL;
    }
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], strDesURL];
    [_uploadFile changeURL:strRequestURL];

    if(_receiverTF.text.length==0)
    {
        [BIDGlobalMethods showAlertView:@"请选择接收人员" buttonTitle:@"关闭" delegate:nil tag:0];
        return;
    }
    
    NSString *strTitle = _titleTF.text.length>0?_titleTF.text:@"";
    NSString *strContent = _contentTextView.text.length>0?_contentTextView.text:@"";
    if(_addPhotoView.imgArr.count>0)
    {
        [_uploadFile addData:@"receiveId" value:receiverIDs];
        [_uploadFile addData:@"userId" value:[AppDelegate getUserId]];
        [_uploadFile addData:@"title" value:strTitle];
        [_uploadFile addData:@"content" value:strContent];
        for(int i=0; i<_addPhotoView.imgArr.count; i++)
        {
            NSString *strName = [[NSString alloc] initWithFormat:@"img%d.jpg", i];
            NSString *strFieldName = @"uploadFile";
            UIImage *img = _addPhotoView.imgArr[i];
            NSData *imgData = UIImageJPEGRepresentation(img, 0.5f);
            [_uploadFile addFileFromMemory:strName fieldName:strFieldName data:imgData];
            [_uploadFile addData:@"fileName" value:strName];
        }
        [_uploadFile finishAddFile];
        [_uploadFile startUpload];
    }
    else
    {
        NSString *strPost = [[NSString alloc] initWithFormat:@"title=%@&content=%@&userId=%@&receiveId=%@", strTitle, strContent, [AppDelegate getUserId], receiverIDs];
        [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary* responseDic, NSString *errMsg){
            if(responseDic)
            {
                [BIDGlobalMethods showAlertView:@"发送成功" buttonTitle:ALERT_BTN_TITLE delegate:self tag:1];
            }
        }];
    }
}

#pragma mark - BIDMemberListViewControllerDelegate
- (void)getChoosedMember:(NSString *)ids andNames:(NSString *)names
{
    NSArray *arr = [names componentsSeparatedByString:@","];
    if(arr && arr.count>5)
    {
        _receiverTF.text = [[NSString alloc] initWithFormat:@"%@,%@等%ld人", arr[0], arr[1], arr.count];
    }
    else if(arr)
    {
        _receiverTF.text = names;
    }
    receiverIDs = ids;
}

#pragma mark - BIDAddPhotoViewDelegate
- (void)choosePhoto
{
    if(_addPhotoView.imgArr.count == 3)
    {
        [self showAlertView:@"最多选择3张图片" buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        return;
    }
    //
    ELCImagePickerController *elcPicker = [[ELCImagePickerController alloc] initImagePicker];
    
    //
    elcPicker.maximumImagesCount = 3-_addPhotoView.imgArr.count; //Set the maximum number of images to select to 100
    elcPicker.returnsOriginalImage = YES; //Only return the fullScreenImage, not the fullResolutionImage
    elcPicker.returnsImage = YES; //Return UIimage if YES. If NO, only return asset location information
    elcPicker.onOrder = YES; //For multiple image selection, display and return order of selected images
    elcPicker.mediaTypes = @[(NSString *)kUTTypeImage]; //Supports image and movie types((NSString *)kUTTypeMovie)
    
    elcPicker.imagePickerDelegate = self;
    
    [self presentViewController:elcPicker animated:YES completion:nil];
}

- (void)resizeViewWithFrame:(CGRect)frame
{
    _heightForAddPhotoViewConstraint.constant = CGRectGetHeight(frame);
    _heightForContainerViewConstraint.constant = CGRectGetMaxY(frame) + 8;//CGRectGetMinY(_addPhotoView.frame)+CGRectGetHeight(frame)+8;
    //[self.view layoutIfNeeded];
    CGSize contentSize = _scrollView.contentSize;
    contentSize.height = CGRectGetHeight(_containerView.frame);
    [_scrollView setContentSize:contentSize];
}

- (void)showPhotoAtIndex:(NSInteger)index withImgArr:(NSArray *)arr
{
    BIDBrowserImageViewController *vc = [[BIDBrowserImageViewController alloc] initWithNibName:@"BIDBrowserImageViewController" bundle:nil];
    vc.imgArr = arr;
    vc.index = index;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - ELCImagePickerControllerDelegate Methods

- (void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info
{
    [self dismissViewControllerAnimated:YES completion:nil];
    
    NSMutableArray *images = [NSMutableArray arrayWithCapacity:[info count]];
    for (NSDictionary *dict in info)
    {
        if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypePhoto)
        {
            if ([dict objectForKey:UIImagePickerControllerOriginalImage])
            {
                UIImage* image=[dict objectForKey:UIImagePickerControllerOriginalImage];
                [images addObject:image];
                [_addPhotoView addPhoto:image];
            }
            else
            {
                NSLog(@"UIImagePickerControllerReferenceURL = %@", dict);
            }
        }
        else if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypeVideo)
        {
            if ([dict objectForKey:UIImagePickerControllerOriginalImage])
            {
                UIImage* image=[dict objectForKey:UIImagePickerControllerOriginalImage];
                [images addObject:image];
            }
            else
            {
                NSLog(@"UIImagePickerControllerReferenceURL = %@", dict);
            }
        }
        else
        {
            NSLog(@"Uknown asset type");
        }
    }
    _chosenImgArr = images;
}

- (void)elcImagePickerControllerDidCancel:(ELCImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if(textField.tag == 1)
    {
        [textField resignFirstResponder];
        BIDMemberListViewController *vc = [[BIDMemberListViewController alloc] init];
        vc.chooseType = TYPE_CHECK;
        vc.delegate = self;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark - BIDUploadFileDelegate
/**
 *  发送通知成功
 *
 *  @param data <#data description#>
 */
- (void)finishUploadWithResult:(id)obj
{
    if([obj isKindOfClass:[NSDictionary class]])
    {
        NSDictionary *dic = (NSDictionary*)obj;
        NSNumber *value = dic[@"isSuccess"];
        if(!ISNULL(value))
        {
            if([value intValue] == 1)
            {
                [BIDGlobalMethods showAlertView:@"发送成功" buttonTitle:ALERT_BTN_TITLE delegate:self tag:1];
            }
            else
            {
                [BIDGlobalMethods showAlertView:@"发送失败" buttonTitle:ALERT_BTN_TITLE delegate:nil tag:0];
            }
        }
        else
        {
        }
    }
}
/**
 *  失败
 *
 *  @param err <#err description#>
 */
- (void)uploadFailedWithError:(NSError *)err
{
    [BIDGlobalMethods showAlertView:[err localizedDescription] buttonTitle:ALERT_BTN_TITLE delegate:nil tag:0];
}

#pragma mark - BIDShowPhotoViewDelegate
- (void)changeStatusForStatusBar:(NSInteger)type
{
    if(type==1)
    {
        [[UIApplication sharedApplication] setStatusBarHidden:NO];
    }
    else
    {
        [[UIApplication sharedApplication] setStatusBarHidden:YES];
    }
}



#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(alertView.tag==1)
    {
        //发送邮件成功
        [self.navigationController popViewControllerAnimated:YES];
    }
}

@end
